﻿@model  IEnumerable<Logic.Models.WorkItem>

@{
    Layout = null;
}

    <div id="tableContainer">
    </div>
    <script src="/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        function stringFormat(str, arr)
        {
            if (!$.isArray(arr))
                arr = $.grep(arguments, function (item, index) { return index != 0; });
            
            return str.replace(/\{([0-9]+)\}/g, function (wholematch, firstmatch)
            {
                return arr[(+firstmatch)];
            });
        }

        function ProjectTable(container, states, roles)
        {
            ProjectTable.count = ProjectTable.count? ProjectTable.count + 1: 1;
            this.projects = projects;
            this.container = $(container);
            this.states = states;
            this.roles = roles;

            this.render = function (projects)
            {
                this.projects = projects;
                this.container.append(this.getControls());
                table = $(this.getTable());
                this.container.append(table);
                table.append(this.getHeader());
                if(!table.find('tbody').length)
                    table.append(stringFormat("<tbody></tbody>"));
                this.loadProjects();
                var thisTable = this;

                $('.nameFilter', this.container).keyup(function()
                {
                    var timeout = 400;
                    var filter =  $(this);
                    var value = filter.val();
                    window.setTimeout(function()
                    {
                        if(filter.val() == value)
                             thisTable.filter();
                    }, timeout);
                });

                $('.stateFilter, .roleFilter', this.container).change(function()
                {
                    thisTable.filter();
                });
            }

            this.filter = function()
            {
                var filter = $('.nameFilter', this.container).val();
                var state = $('.stateFilter', this.container).val();
                var role = $('.roleFilter', this.container).val();
                
                var thisTable = this;
                $('#filterImg').show();
                $.ajax({
                            type: "POST",
                            url: "/Test/WorkItemChildren",
                            dataType: "json",
                            data:   {filter:filter, state:state, role:role},
                            success: function (res) 
                            {
                                
                                $('#filterImg').hide();
                                thisTable.projects = res;
                                thisTable.loadProjects();
                            },
                        });
            };

            this.loadProjects = function()
            {
                thisTable = this;
                
                this.container.find('tbody').html('');
                this.container.find('tbody').append(this.getRows(this.projects, 0));
                
                $('tr', table).click(function()
                {
                    $('tr', table).removeClass('SelectedRow');
                    $(this).addClass('SelectedRow');
                });

                $('.item .open', table).click(function()
                {
                    thisTable.fetchChildren.call(thisTable, this);
                })
            }

            this.getTable = function()
            {
                return stringFormat("<table id='{0}' cellspacing='0' class='{1}'></table>", "projectTable" + ProjectTable.count, "projectTable");
            }

            this.getControls = function()
            {
                
                return stringFormat("<div cellspacing='0' class='{0}'>\
                                        <select class='stateFilter'>{1}</select>\
                                        <select class='roleFilter'>{2}</select>\
                                        <input class='nameFilter' type='text'/>\
                                        <img id='filterImg' style='display:none' src='/Images/treeview/ajax-loader.gif'/>\
                                     </div>"
                                     ,"controls"
                                     ,this.states.map(function(el)
                                     {
                                        return stringFormat("<option>{0}</option>",el);
                                     }).join('')
                                     ,this.roles.map(function(el)
                                     {
                                        return stringFormat("<option>{0}</option>",el);
                                     }).join(''));
            }

            this.fetchChildren = function(element)
            {
                var tr = $(element).closest('tr');
                var parentID = tr.attr('id');
                var parentType = tr.attr('itemType');
                var thisTable = this;

                if($(element).data('open'))
                {
                    $(element).data('open',false);
                    $(element).attr('src', '/Images/tree_open.gif')
                    this.hideChildren(parentID);
                }
                else if($('[parentID="' + parentID + '"]').length)
                {
                    $(element).data('open',true);
                    $('[parentID="' + parentID + '"]').show();
                    $(element).attr('src', '/Images/tree_close.gif');

                }
                else
                {
                    $(element).attr('src', '/Images/treeview/ajax-loader.gif');
                    
                    $.ajax({
                        type: "POST",
                        url: "/Test/WorkItemChildren",
                        dataType: "json",
                        data:   {parentID:parentID, parentType:parentType},
                        success: function (res) 
                        {
                            if(!res || res.length == 0)
                                $(element).css('visibility','hidden');
                            
                            $(element).data('open',true);
                            thisTable.addChildren(parentID, res);
                            $(element).attr('src', '/Images/tree_close.gif');
                            
                            $('[parentID="' + parentID + '"]', table).click(function()
                            {
                                $('tr', table).removeClass('SelectedRow');
                                $(this).addClass('SelectedRow');
                            })

                            $('[parentID="' + parentID + '"] .open', table).click(function()
                            {
                                thisTable.fetchChildren.call(thisTable, this);
                            })
                        },
                    });
                }
            }

            this.getHeader = function()
            {
                var html = stringFormat("<tr class='header'>");
                html += stringFormat("<td></td>","");//active icon
                html += stringFormat("<td></td>","Name");// type icon
                html += stringFormat("<td>{0}</td>","Project");
                html += stringFormat("<td>{0}</td>","Start Date");
                html += stringFormat("<td>{0}</td>","Due Date");
                html += stringFormat("</tr>");

                return html;
            }

            this.getRows = function(items, depth, parentID)
            {
                var html = "";
                for(var i=0; i<items.length; i++)
                    html += this.getRow(items[i], depth, parentID);

                return html;
            }

            this.getRow = function(project, depth, parentID)
            {
                var html = stringFormat("<tr id='{0}'  itemType='{1}' parentID='{2}' class='item' depth='{3}'>", project.ID.Value,project.ID.TypeName, parentID, depth);
                
                html += stringFormat("<td class='status'><img src='/Images/{0}'/></td>",this.getStatusImage(project));
                html += stringFormat("<td class='type' style='padding-left:{1}px'><img class='open' src='/Images/tree_open.gif'/><img class='typeImg' src='/Images/{0}'/>{2}</td>",this.getTypeImage(project), (+depth) * 20, project.Name);
                html += stringFormat("<td class=''>{0}</td>",project.ParentProject_Name? project.ParentProject_Name: "");
                html += stringFormat("<td class=''>{0}</td>",project.StartDateString);
                html += stringFormat("<td class=''>{0}</td>",project.DueDateString);
                
                html += stringFormat("</tr>");

                return html;
            }

            this.addChildren = function(parentID, workItems)
            {
                var parent = $('#' + parentID);
                var depth = (+parent.attr('depth')) + 1;
                var index = parent.find('td:first').html();
                var newRows = this.getRows(workItems, depth, parentID);
                parent.after(newRows);
            }

            this.getStatusImage = function(workItem)
            {
                switch(workItem.TrackStatus.Id.Value.toLowerCase())
                {
                    case "not active":
                        return "iconNotActive.jpg";
                        break;
                    case "at risk":
                        return "iconAtRisk.jpg";
                        break;
                    case "off track":
                        return "iconOffTrack.jpg";
                        break;
                    case "on track":
                    default:
                        return "iconOnTrack.jpg";
                        break;
                }
            }

            this.getTypeImage = function(workItem)
            {
                switch(workItem.ID.TypeName.toLowerCase())
                {
                    case "project":
                        return "iconProject.jpg";
                        break;
                    case "milestone":
                        return "iconMilestone.jpg";
                        break;
                    case "task":
                    default:
                        return "iconTask.jpg";
                        break;
                }
            }

            this.hideChildren = function(parentID)
            {
                var table = this;
                $('[parentID="' + parentID + '"]').hide().each(function()
                {
                    $('.open',this).attr('src', '/Images/tree_open.gif').data('open', false);
                    var id = $(this).attr('id');
                    table.hideChildren(id);
                });
            }
        }

        var projects =  @(Html.Raw(Logic.Extentions.ToJson(Model)));
        var states =  @(Html.Raw(Logic.Extentions.ToJson(Enum.GetNames(typeof(Logic.ClarizenSvc.WorkItemState)))));
        var roles = @(Html.Raw(Logic.Extentions.ToJson(Enum.GetNames(typeof(Logic.ClarizenSvc.WorkItemFilter)))));
        var pTable = new ProjectTable('#tableContainer',states, roles);
        pTable.render(projects);
    </script>


    <style>
        .projectTable       {font-size:12px;border: 3px solid #8FC6FF;-moz-border-radius: 5px;-webkit-border-radius: 5px;}
        .projectTable tr td {border-bottom:solid 1px #EFEFEF; color:#666; padding:3px 6px}
        .projectTable .typeImg  {margin-right:5px}
        .projectTable img       {}
        .projectTable .SelectedRow  {background-color: rgb(206, 228, 255)}
        
        .projectTable .header       {background: url("/Images/BGHeader.gif") repeat-x; background-position:0px -57px ; height:22px}
        .projectTable .header td    {border-right:solid 1px #dEf4FF; text-align:center}
    </style>
